const Banner = require('../models/Banner');
const { validationResult } = require('express-validator');
const mongoose = require('mongoose');

/**
 * 获取轮播图列表 (管理员)
 * GET /api/admin/banners
 */
exports.getBanners = async (req, res, next) => {
  try {
    const {
      keyword = '',
      platform = '',
      isActive = '',
      page = 1,
      limit = 10,
      sort = '-createdAt'
    } = req.query;

    // 构建查询条件
    const query = {};

    // 关键词搜索
    if (keyword) {
      query.$or = [
        { title: { $regex: keyword, $options: 'i' } },
        { description: { $regex: keyword, $options: 'i' } }
      ];
    }

    // 平台过滤
    if (platform) {
      query.platform = platform;
    }

    // 状态过滤
    if (isActive !== '') {
      query.isActive = isActive === 'true';
    }

    // 分页
    const pageNumber = parseInt(page);
    const limitNumber = parseInt(limit);
    const skip = (pageNumber - 1) * limitNumber;

    // 排序处理
    const sortObj = {};
    if (sort.startsWith('-')) {
      sortObj[sort.substring(1)] = -1;
    } else {
      sortObj[sort] = 1;
    }

    // 获取总数
    const total = await Banner.countDocuments(query);

    // 获取轮播图数据
    const banners = await Banner.find(query)
      .populate('createdBy', 'name email')
      .populate('updatedBy', 'name email')
      .sort(sortObj)
      .skip(skip)
      .limit(limitNumber)
      .lean();

    // 添加虚拟字段
    const bannersWithStatus = banners.map(banner => {
      const now = new Date();
      const startValid = !banner.startDate || banner.startDate <= now;
      const endValid = !banner.endDate || banner.endDate >= now;
      const isValid = banner.isActive && startValid && endValid;

      return {
        ...banner,
        isValid,
        id: banner._id
      };
    });

    res.json({
      success: true,
      data: bannersWithStatus,
      pagination: {
        current: pageNumber,
        pageSize: limitNumber,
        total,
        pages: Math.ceil(total / limitNumber)
      }
    });
  } catch (error) {
    console.error('获取轮播图列表失败:', error);
    next(error);
  }
};

/**
 * 获取单个轮播图详情 (管理员)
 * GET /api/admin/banners/:id
 */
exports.getBanner = async (req, res, next) => {
  try {
    const { id } = req.params;

    if (!mongoose.Types.ObjectId.isValid(id)) {
      return res.status(400).json({
        success: false,
        message: '无效的轮播图ID'
      });
    }

    const banner = await Banner.findById(id)
      .populate('createdBy', 'name email')
      .populate('updatedBy', 'name email');

    if (!banner) {
      return res.status(404).json({
        success: false,
        message: '轮播图不存在'
      });
    }

    res.json({
      success: true,
      data: {
        ...banner.toObject(),
        id: banner._id
      }
    });
  } catch (error) {
    console.error('获取轮播图详情失败:', error);
    next(error);
  }
};

/**
 * 创建轮播图 (管理员)
 * POST /api/admin/banners
 */
exports.createBanner = async (req, res, next) => {
  try {
    // 验证请求数据
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '数据验证失败',
        errors: errors.array()
      });
    }

    const {
      title,
      image,
      link = '',
      linkType = 'none',
      linkTarget = '',
      order = 0,
      isActive = true,
      startDate,
      endDate,
      description = '',
      platform = 'all'
    } = req.body;

    // 创建轮播图
    const banner = new Banner({
      title,
      image,
      link,
      linkType,
      linkTarget,
      order,
      isActive,
      startDate: startDate ? new Date(startDate) : new Date(),
      endDate: endDate ? new Date(endDate) : null,
      description,
      platform,
      createdBy: req.user.id
    });

    await banner.save();

    // 返回创建的轮播图（包含关联数据）
    const createdBanner = await Banner.findById(banner._id)
      .populate('createdBy', 'name email');

    res.status(201).json({
      success: true,
      message: '轮播图创建成功',
      data: {
        ...createdBanner.toObject(),
        id: createdBanner._id
      }
    });
  } catch (error) {
    console.error('创建轮播图失败:', error);
    next(error);
  }
};

/**
 * 更新轮播图 (管理员)
 * PUT /api/admin/banners/:id
 */
exports.updateBanner = async (req, res, next) => {
  try {
    const { id } = req.params;

    if (!mongoose.Types.ObjectId.isValid(id)) {
      return res.status(400).json({
        success: false,
        message: '无效的轮播图ID'
      });
    }

    // 验证请求数据
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '数据验证失败',
        errors: errors.array()
      });
    }

    const updateData = {
      ...req.body,
      updatedBy: req.user.id
    };

    // 处理日期字段
    if (updateData.startDate) {
      updateData.startDate = new Date(updateData.startDate);
    }
    if (updateData.endDate) {
      updateData.endDate = new Date(updateData.endDate);
    }

    const banner = await Banner.findByIdAndUpdate(
      id,
      updateData,
      { new: true, runValidators: true }
    ).populate('createdBy', 'name email')
      .populate('updatedBy', 'name email');

    if (!banner) {
      return res.status(404).json({
        success: false,
        message: '轮播图不存在'
      });
    }

    res.json({
      success: true,
      message: '轮播图更新成功',
      data: {
        ...banner.toObject(),
        id: banner._id
      }
    });
  } catch (error) {
    console.error('更新轮播图失败:', error);
    next(error);
  }
};

/**
 * 删除轮播图 (管理员)
 * DELETE /api/admin/banners/:id
 */
exports.deleteBanner = async (req, res, next) => {
  try {
    const { id } = req.params;

    if (!mongoose.Types.ObjectId.isValid(id)) {
      return res.status(400).json({
        success: false,
        message: '无效的轮播图ID'
      });
    }

    const banner = await Banner.findByIdAndDelete(id);

    if (!banner) {
      return res.status(404).json({
        success: false,
        message: '轮播图不存在'
      });
    }

    res.json({
      success: true,
      message: '轮播图删除成功'
    });
  } catch (error) {
    console.error('删除轮播图失败:', error);
    next(error);
  }
};

/**
 * 批量删除轮播图 (管理员)
 * POST /api/admin/banners/batch-delete
 */
exports.batchDeleteBanners = async (req, res, next) => {
  try {
    const { ids } = req.body;

    if (!Array.isArray(ids) || ids.length === 0) {
      return res.status(400).json({
        success: false,
        message: '请提供要删除的轮播图ID列表'
      });
    }

    // 验证所有ID格式
    const invalidIds = ids.filter(id => !mongoose.Types.ObjectId.isValid(id));
    if (invalidIds.length > 0) {
      return res.status(400).json({
        success: false,
        message: '包含无效的轮播图ID',
        invalidIds
      });
    }

    const result = await Banner.deleteMany({
      _id: { $in: ids }
    });

    res.json({
      success: true,
      message: `成功删除 ${result.deletedCount} 个轮播图`,
      deletedCount: result.deletedCount
    });
  } catch (error) {
    console.error('批量删除轮播图失败:', error);
    next(error);
  }
};

/**
 * 更新轮播图状态 (管理员)
 * PATCH /api/admin/banners/:id/status
 */
exports.updateBannerStatus = async (req, res, next) => {
  try {
    const { id } = req.params;
    const { isActive } = req.body;

    if (!mongoose.Types.ObjectId.isValid(id)) {
      return res.status(400).json({
        success: false,
        message: '无效的轮播图ID'
      });
    }

    if (typeof isActive !== 'boolean') {
      return res.status(400).json({
        success: false,
        message: '状态值必须为布尔类型'
      });
    }

    const banner = await Banner.findByIdAndUpdate(
      id,
      {
        isActive,
        updatedBy: req.user.id
      },
      { new: true }
    );

    if (!banner) {
      return res.status(404).json({
        success: false,
        message: '轮播图不存在'
      });
    }

    res.json({
      success: true,
      message: `轮播图已${isActive ? '启用' : '禁用'}`,
      data: {
        ...banner.toObject(),
        id: banner._id
      }
    });
  } catch (error) {
    console.error('更新轮播图状态失败:', error);
    next(error);
  }
};
